package com.android.antelopeapp.view.BeautyPic;

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.antelopeapp.R;
import com.lyhw.model.ImageTag;

/**
 * Created by phk on 2014/12/21.
 * 要求控件所在的布局为FrameLayout
 * 为图片添加标签的视图
 * 内容分为两部分
 * 1.标签标志图片（小圆点）
 * 2.标签内容（图标+文字）
 * 功能实现:
 * 交互：
 * 1.自由拖动
 * 2.点击一次提示是否删除该标签
 * 3.长按改变标签方向
 * 可以设置是否允许交互
 */
public class ImageTagBox extends RelativeLayout {
    public static final String TAG = "ImageTagBox";
    private static final int INVALID_POINTER_ID = -1;
    // The ‘active pointer’ is the one currently moving our object.
    private int mActivePointerId = INVALID_POINTER_ID;
    //控件容器
    private boolean mIsInteractive = true;
    //tag实例
    private ImageTag mImgTag;
    //屏幕大小
    private int mParentWidth;
    private int mParentHeight;
    private float mLastTouchX;
    private float mLastTouchY;
    private boolean mIsMoved;
    private boolean mEnableMove = true;
    private GestureDetector mGestureDetector ;

    private TextView mtextView;


    public int getTextWidth(){
        if(mtextView == null){
            return 0;
        }
        return mtextView.getWidth();
    }

    public static int s_uniform_width;

    public ImageTagBox(Context context) {
        super(context);
    }

    public ImageTagBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageTagBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ImageTagBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void setParentBound(int parentWidth, int parentHeight) {
        this.mParentWidth = parentWidth;
        this.mParentHeight = parentHeight;
    }


    /**
     * 根据父控件的高度宽度调整当前控件的位置
     * */
    public  void updatePos(FrameLayout parent){
        if(parent != null){
            setParentBound(parent.getWidth(),parent.getHeight());
        }
        updateLayoutParam();
    }

    /**
     * 绑定imagetag
     */
    public void bindImageTag(ImageTag tag) {
        //todo 更多操作需要完善 包括标签类型 标签内容 标签位置
        mImgTag = tag;
        mtextView = (TextView) this.findViewById(R.id.imgtagbox_text);
        if(tag.getmText().equals("")){
            //todo 名字需要规范
            tag.setmText(" ");
        }
        mtextView.setText(tag.getmText());
    }

    private int transX2L(int x){
        if(mImgTag.getmDir() == 1) {
            return x - getMeasuredWidth();
        }
        return x;
    }
    private int transL2X(int l){
        if(mImgTag.getmDir() == 1) {
            return l + getMeasuredWidth();
        }
        return l;
    }

    /**
     * 更新imgtag的坐标
     * */
    public void updateXY(){
        Log.d("updateXY","left:"+this.getX()+" transL2XLeft:"+transL2X((int)this.getX()));
        this.getmImgTag().setmXP((float)transL2X((int)this.getX())/mParentWidth);
        this.getmImgTag().setmYP(this.getY()/mParentHeight);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if(mGestureDetector != null) {
            mGestureDetector.onTouchEvent(ev);
        }

        if (mEnableMove) {
            final int action = MotionEventCompat.getActionMasked(ev);

            switch (action) {
                case MotionEvent.ACTION_DOWN: {
                    final int pointerIndex = MotionEventCompat.getActionIndex(ev);
                    final float x = ev.getRawX();
                    final float y = ev.getRawY();

                    // Remember where we started (for dragging)
                    mLastTouchX = x;
                    mLastTouchY = y;
                    // Save the ID of this pointer (for dragging)
                    mActivePointerId = MotionEventCompat.getPointerId(ev, 0);

                    //设置为未移动
                    mIsMoved = false;
                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    // Find the index of the active pointer and fetch its position
                    final int pointerIndex =
                            MotionEventCompat.findPointerIndex(ev, mActivePointerId);

                    final float x = ev.getRawX();
                    final float y = ev.getRawY();

                    // Calculate the distance moved
                    final float dx = x - mLastTouchX;
                    final float dy = y - mLastTouchY;

                    Log.v(TAG, "ACTION_MOVE dx :" + dx + " dy:" + dy);
                    float nextx = this.getX() + dx;
                    float nexty = this.getY() + dy;
                    nextx = nextx < 0 ? 0 : (nextx > mParentWidth - this.getWidth() ? mParentWidth - this.getWidth() : nextx);
                    nexty = nexty < 0 ? 0 : (nexty > mParentHeight - this.getHeight() ? mParentHeight - this.getHeight() : nexty);

                    this.setX(nextx);
                    this.setY(nexty);
                    this.updateXY();

                    if(Math.abs(dx)<5 && Math.abs(dy)<5){

                    }else {
                    }

                    invalidate();

                    if (Math.abs(dx) < 0.1 && Math.abs(dy) < 0.1) {
                        mIsMoved = false;
                    } else {
                        mIsMoved = true;
                    }
                    // Remember this touch position for the next move event
                    mLastTouchX = x;
                    mLastTouchY = y;

                }

                case MotionEvent.ACTION_UP: {
                    mActivePointerId = INVALID_POINTER_ID;
                    break;
                }
            }
           return mIsMoved ? true : super.onTouchEvent(ev);
        } else {
            return true;
        }
    }

    public void updateLayoutParam(){
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) this.getLayoutParams();
        int x = (int) (mImgTag.getmXP() * mParentWidth);
        int y = (int) (mImgTag.getmYP() * mParentHeight);

        layoutParams.setMargins(transX2L(x), y, 0, 0);

        Log.v(TAG, "updateLayout~ parentW:" + mParentWidth + " parentH:" + mParentHeight + " x:" + x + " y:" + y+" measureWidth:"+getMeasuredWidth());
    }

    public boolean ismEnableMove() {
        return mEnableMove;
    }

    public void setmEnableMove(boolean mEnableMove) {
        this.mEnableMove = mEnableMove;
    }

    public ImageTag getmImgTag() {
        return mImgTag;
    }

    public void setmImgTag(ImageTag mImgTag) {
        this.mImgTag = mImgTag;
    }

    public void updateTag() {
        if (mImgTag != null) {
            bindImageTag(mImgTag);
        }
    }

    public void setmGestureDetector(GestureDetector.OnGestureListener OnGestureListener) {
        this.mGestureDetector = new GestureDetector(this.getContext(),OnGestureListener);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }
}
